package edu.zjut.hjg.saas.kwmp.web.controller.teacher;

import static edu.zjut.hjg.saas.kwmp.web.support.KwmpConstants.SESSION_NAME_USER;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import edu.zjut.hjg.saas.biz.model.CookBook;
import edu.zjut.hjg.saas.biz.model.Kindergarten;
import edu.zjut.hjg.saas.biz.model.Recipe;
import edu.zjut.hjg.saas.biz.service.RecipeService;
import edu.zjut.hjg.saas.common.annotation.CookieSessionIn;
import edu.zjut.hjg.saas.common.annotation.RequestAttribute;
import edu.zjut.hjg.saas.common.util.ParameterUtil;
import edu.zjut.hjg.saas.kwmp.web.model.UserSession;

@Controller
@RequestMapping("/teacher/recipe")
public class RecipeManageController {

    @Autowired
    private RecipeService recipeService;

    @RequestMapping("index.htm")
    public String index(@RequestAttribute Kindergarten app, Model model) {
        Recipe recipe = recipeService.findByAppId(app.getId());
        if (recipe != null) {
            model.addAttribute("cookBook", recipe.getCookBook());
            model.addAttribute("theWeek", recipe.getTheWeek());
        }
        return "teacher/recipe";
    }

    @CookieSessionIn(value = SESSION_NAME_USER, param = "session")
    @RequestMapping(value = "edit.htm", method = RequestMethod.POST)
    public String edit(@RequestAttribute Kindergarten app, UserSession session, Model model,
                       CookBook cookBook, int theWeek) {
        model.addAttribute("theWeek", theWeek);
        if (!ParameterUtil.notBlank(cookBook, theWeek)) {
            model.addAttribute("errorMsg", "请填写完整");
            model.addAttribute("cookBook", cookBook);
            return "teacher/recipe";
        }
        recipeService.edit(app.getId(), session.getId(), cookBook, theWeek, session.getLoginId());
        model.addAttribute("message", "编辑本周食谱成功");
        return "teacher/recipe";
    }
}
